function PostEditorAssistant(argFromPusher) {
}

function xmlencode(string) {
    return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
        .replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}

function xmldecode(string) {
    return string.replace(/\&amp;/g,'&').replace(/\&lt;/g,'<')
        .replace(/\&gt;/g,'>').replace(/&apos;/g,'\'').replace(/&quot;/g,'"');
}

PostEditorAssistant.prototype = {
	setup: function() {
		Ares.setupSceneAssistant(this);
		
		this.showingHtml = false;
		
		this.controller.setupWidget(Mojo.Menu.appMenu, this.attributes = {richTextEditMenu: true}, this.model = {});
		
		this.controller.setupWidget(Mojo.Menu.viewMenu,
			{
				spacerHeight: 45
			},
			{
				visible: true,
				items: [
					{
						toggleCmd: "show_compose",
						items: [
							{label: "HTML", width: Mojo.Environment.DeviceInfo.screenWidth/2, command: "show_html"},
							{label: "Compose", width: Mojo.Environment.DeviceInfo.screenWidth/2, command: "show_compose"}
						]
					}
				]
			}
		);
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined,
		{
			visible: true,
			items:
			[
				{label: "Post", icon: "send", command: "post"},
				{label: "Save Draft", icon: "save", command: "save_draft"}
			]
		});
		
		this.postEditorSpinner = this.controller.get("postEditorSpinner");
		this.controller.setupWidget("postEditorSpinner", {'spinnerSize':Mojo.Widget.spinnerLarge}, this.spinnerModel = {'spinning': true});
		this.postEditorSpinnerScrim = Mojo.View.createScrim(this.controller.document, {scrimClass: 'palm-scrim'});
		this.postEditorSpinnerScrim.hide();
		this.controller.get("postEditorScrimContainer").appendChild(this.postEditorSpinnerScrim).appendChild(this.postEditorSpinner);
		
		//this.controller.get("postBody").setAttribute("style", this.controller.get("postBody").getAttribute("style") + " background: yellow;");
	},
	cleanup: function() {
		Ares.cleanupSceneAssistant(this);
	},
	activate: function()
	{
		if (activePostID)
		{
			if (activePostXML.getElementsByTagName("title")[0].childNodes.length > 0)
			{
				this.$.postTitleTextField.setValue(activePostXML.getElementsByTagName("title")[0].childNodes[0].nodeValue);
			}
			if (activePostXML.getElementsByTagName("content")[0].childNodes.length > 0)
			{
				this.controller.get("postBody").innerHTML = activePostXML.getElementsByTagName("content")[0].childNodes[0].nodeValue;
			}
		}
		else 
		{
			this.controller.get("postBody").setAttribute("style", this.controller.get("postBody").getAttribute("style") + " width: 100%; height: 100%;");
		}
		
		//this.controller.get("postEditorScroller").mojo.adjustBy(0, -62);
		//Mojo.Log.info("left: " + this.controller.getSceneScroller().mojo.getScrollPosition().left);
		//Mojo.Log.info("top: " + this.controller.getSceneScroller().mojo.getScrollPosition().top);
	},
	
	handleCommand: function(event)
	{
		if (event.type == Mojo.Event.command)
		{
			switch (event.command)
			{
				case "post":
					this.updatePost(false);
					break;
				case "save_draft":
					this.updatePost(true);
					break;
				case "show_compose":
					if (this.showingHtml === true)
					{
						this.controller.get("postBody").innerHTML = xmldecode(this.controller.get("postBody").innerHTML);
						this.controller.get("postBody").setAttribute("class", "post-body post-body-standard");
						this.showingHtml = false;
					}
					break;
				case "show_html":
					if (this.showingHtml === false)
					{
						this.controller.get("postBody").innerHTML = xmlencode(this.controller.get("postBody").innerHTML);
						this.controller.get("postBody").setAttribute("class", "post-body post-body-html");
						this.showingHtml = true;
					}
					break;
				default:
					break;
			}
		}
		else if (event.type == Mojo.Event.back)
		{
			if ( //check to see if anything changed before showing alert
				(activePostID && activePostXML.getElementsByTagName("title")[0].childNodes.length > 0 &&
				 activePostXML.getElementsByTagName("title")[0].childNodes[0].nodeValue != this.$.postTitleTextField.getValue()) ||
				(activePostID && activePostXML.getElementsByTagName("content")[0].childNodes.length > 0 &&
				 activePostXML.getElementsByTagName("content")[0].childNodes[0].nodeValue != this.controller.get("postBody").innerHTML) ||
				((!activePostID || activePostXML.getElementsByTagName("title")[0].childNodes.length === 0) && this.$.postTitleTextField.getValue().length > 0) ||
				((!activePostID || activePostXML.getElementsByTagName("content")[0].childNodes.length === 0) && this.controller.get("postBody").innerHTML.length > 0)
				)
			{
				event.stop();
				this.controller.showAlertDialog(
				{
					onChoose: function(value)
					{
						if (value == "post")
						{
							this.updatePost(false);
						}
						else if (value == "lose_changes")
						{
							this.controller.stageController.popScene();
						}
						else //default to save draft
						{
							this.updatePost(true);
						}
					},
					title: "Unsaved Changes",
					message: "There may be unsaved changes.  Do you want to post, save as draft, or lose changes?",
					preventCancel: true,
					choices: [
						{label: "Post", value: "post"},
						{label: "Save Draft", value: "save_draft", type: "affirmative"},
						{label: "Lose Changes", value: "lose_changes", type: "negative"}
					]
				});
			}
		}
	},
	
	updatePost: function(asDraft)
	{
		this.postEditorSpinnerScrim.show();
		var postXML = null;
		var postRequest = null;
		if (activePostID)  //post already exists, just updating it
		{
			var titleIsBlank = false;
			var contentIsBlank = false;
			if (activePostXML.getElementsByTagName("title")[0].childNodes.length > 0)
			{
				activePostXML.getElementsByTagName("title")[0].childNodes[0].nodeValue = this.$.postTitleTextField.getValue();
			}
			else
			{
				titleIsBlank = true;
			}
			
			if (activePostXML.getElementsByTagName("content")[0].childNodes.length > 0)
			{
				var postHtml;
				if (this.showingHtml === true) {postHtml = xmldecode(this.controller.get("postBody").innerHTML);}
				else {postHtml = this.controller.get("postBody").innerHTML;}
				
				activePostXML.getElementsByTagName("content")[0].childNodes[0].nodeValue = postHtml;
			}
			else
			{
				contentIsBlank = true;
			}
			
			var draftRe = /<app:control[^]*app:control>/;
			postXML = (new XMLSerializer()).serializeToString(activePostXML);
			if (titleIsBlank === true)
			{
				postXML = postXML.replace(/<title type="text"\/>/, "<title type='text'>" + this.$.postTitleTextField.getValue() + "</title>");
			}
			if (contentIsBlank === true)
			{
				postXML = postXML.replace(/<content type="html"\/>/, "<content type='html'>" + this.controller.get("postBody").innerHTML + "</content>");
			}
			if (postXML.match(draftRe))
			{
				if (asDraft === true)
				{
					postXML = postXML.replace(draftRe, "<app:control xmlns:app='http://purl.org/atom/app#'><app:draft>yes</app:draft></app:control>");
				}
				else
				{
					postXML = postXML.replace(draftRe, "<app:control xmlns:app='http://purl.org/atom/app#'><app:draft>no</app:draft></app:control>");
				}
			}
			else
			{
				if (asDraft === true)
				{
					postXML = postXML.replace(/>/, "><app:control xmlns:app='http://purl.org/atom/app#'><app:draft>yes</app:draft></app:control>");
				}
			}
			
			Mojo.Log.info(postXML);
			postRequest = new Ajax.Request("http://www.blogger.com/feeds/" + activeBlogID + "/posts/default/" + activePostID,
			{
				method: 'post',
				contentType: 'application/atom+xml',
				postBody: postXML,
				requestHeaders:
				{
					Authorization: 'GoogleLogin auth=' + authCode,
					"X-HTTP-Method-Override": "PUT"
				},
				onSuccess: this.postRequestSuccess.bind(this),
				onFailure: this.postRequestFailure.bind(this)
			});
		}
		else  //new post
		{
			postXML = "<entry xmlns='http://www.w3.org/2005/Atom'>";
			if (asDraft === true)
			{
				postXML += "<app:control xmlns:app='http://purl.org/atom/app#'><app:draft>yes</app:draft></app:control>";
			}
			postXML += "<title type='text'>" + xmlencode(this.$.postTitleTextField.getValue()) +
				"</title><content type='html'>" + xmlencode(this.controller.get("postBody").innerHTML) + "</content></entry>";
			//Mojo.Log.info(postXML);
			postRequest = new Ajax.Request("http://www.blogger.com/feeds/" + activeBlogID + "/posts/default", {
				method: 'post',
				contentType: 'application/atom+xml',
				postBody: postXML,
				requestHeaders: {
					Authorization: 'GoogleLogin auth=' + authCode
				},
				onSuccess: this.postRequestSuccess.bind(this),
				onFailure: this.postRequestFailure.bind(this)
			});
		}
	},
	
	postRequestSuccess: function(postResponse)
	{
		this.controller.stageController.popScene();
		this.postEditorSpinnerScrim.hide();
	},
	
	postRequestFailure: function(postResponse)
	{
		Mojo.Controller.errorDialog(postResponse.responseText);
		this.postEditorSpinnerScrim.hide();
		Mojo.Log.info(postResponse.getAllHeaders());
	}
};